package com.class2.java.service;

import com.alibaba.fastjson.JSONObject;
import com.class2.java.Constants;
import com.class2.java.bean.BlockHash;
import com.class2.java.com.class2.java.net.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:yc
 * @email:1247616535@qq.com
 * @desc: 该类用于实现通过RPC调用比特币客户端的getbestblockhash功能
 * @datetime: 2021/12/26 15:39
 */
public class GetBestBlockHashService {
        //该方法用于请求bitcoin客户端的相应区块的
        public Object getBestBlockHash(){
            //准备rpc请求的用户身份信息
            String auth = Constants.BITCOIN_RPC_USER+":"+Constants.BITCOIN_RPC_PWD;
            //java中实现base64编码
            Base64.Encoder encoder = Base64.getEncoder();
            String authBase64 = encoder.encodeToString(auth.getBytes());

            //准备请求头信息
            Map<String,String> header = new HashMap<>();
            header.put("ContentType","application/json");
            header.put("Authorization","Basic "+authBase64);

            //准备要发送的rpc数据
            Map<String,Object> body = new HashMap<>();
            body.put("id",1001);
            body.put("method","getbestblockhash");
            body.put("params",null);
            body.put("json_rpc","2.0");
            //将map转换成byte[]
            byte[] bodybytes = JSONObject.toJSONBytes(body);

            //格式：{"id":1001,"result":xxxx,"error":null}
            String result = HttpUtils.post(Constants.BITCOIN_RPC_URL,header,bodybytes);
            //json解析
            BlockHash hash = JSONObject.parseObject(result, BlockHash.class);

            return hash.result;
        }

    }

